#include "common.h"

#define STATUS_PIN 13

#define CUE_OFF_PIN 3
#define CUE_1_PIN   4
#define CUE_2_PIN   5
#define CUE_3_PIN   6
#define CUE_4_PIN   7
#define CUE_5_PIN   8 

byte men_on[] =  { ALAN_ON,  CHARLES_ON,  DAVE_ON,  HANSEL_ON,  KEN_ON,  SETH_ON  };
byte men_off[] = { ALAN_OFF, CHARLES_OFF, DAVE_OFF, HANSEL_OFF, KEN_OFF, SETH_OFF };
byte men_except_charles_on[] =  { ALAN_ON, DAVE_ON,  HANSEL_ON,  KEN_ON,  SETH_ON  };

byte women_on[] =  { GUZEL_ON,  KELLY_ON,  KRISTINA_ON,  LAURA_ON,  LINDA_ON,  MARIA_ON  };
byte women_off[] = { GUZEL_OFF, KELLY_OFF, KRISTINA_OFF, LAURA_OFF, LINDA_OFF, MARIA_OFF };

void send_command(byte command) {
  Serial.write(FILLER);
  Serial.write(command);
  Serial.write(command);
  Serial.write(command);
}

void send_commands(byte *commands, int num_commands) {
  Serial.write(FILLER);
  for (int i = 0; i < num_commands; ++i) {
    Serial.write(commands[i]);
    Serial.write(commands[i]);
    Serial.write(commands[i]);
  }
}

typedef enum State {
  ALL_OFF,
  INTRO,
  ALL_ON,
  PINWHEEL,
  TAG,
} State;

State current_state = INTRO;

// Sends out the current state to all receivers.
void transmit_state() {
  switch(current_state) {
  case (INTRO):
    send_commands(women_on, 6);
    send_commands(men_except_charles_on, 5);
    send_command(CHARLES_OFF);
    break;
    
  case (PINWHEEL):
    // TODO(duhadway):
    break;
    
  case (TAG):
    // TODO(duhadway): 
    break;
    
  case (ALL_OFF):
    send_commands(men_off, 6);
    send_commands(women_off, 6);
    break;
    
  case (ALL_ON):
  default:
    send_commands(men_on, 6);
    send_commands(women_on, 6);
    break;  
  }
  
  // Wait for any pending state to be written.  
  Serial.flush();
}

void setup() {
  Serial.begin(9600);
  
  pinMode(STATUS_PIN, OUTPUT);  
  
  pinMode(CUE_1_PIN, INPUT);
  pinMode(CUE_2_PIN, INPUT);
  pinMode(CUE_3_PIN, INPUT);
  pinMode(CUE_4_PIN, INPUT);
  
  digitalWrite(STATUS_PIN, HIGH);
  current_state = INTRO;    
}

void loop() {  
  while (true) {
    transmit_state();
    if (digitalRead(CUE_1_PIN) == HIGH) {
      current_state = INTRO;
    }
    if (digitalRead(CUE_OFF_PIN) == HIGH) {
      current_state = ALL_OFF;
    }
    /*
    Serial.write(FILLER);
    Serial.write(CHARLES_ON);
    Serial.write(CHARLES_ON);
    delay(100);
    Serial.write(FILLER);
    Serial.write(CHARLES_OFF);
    */    
  }
}
